package com.flyzing.genl.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.flyzing.genl.dto.BaseResultMap;
import com.flyzing.genl.dto.ClazzProperty;
import com.flyzing.genl.dto.MapperXMLFile;
import com.flyzing.genl.po.ColumnPO;
import com.flyzing.genl.po.TablePO;
import com.flyzing.genl.util.GenConfigHelper;
import com.flyzing.genl.util.StringUtil;
import com.flyzing.genl.util.TemplateHelper;

/**
 * @author yaoguangyao
 * @Date 2020年12月30日
 */
public class GenMapperXMLFile implements IGenFile{
	
	private static final String CUSTOM_CODE_MARKER = "<!-- O(∩_∩)O -->"; // 自定义代码标记

	@Override
	public void generate(TablePO table, List<ColumnPO> columns) {
		String pathMapperXML = GenConfigHelper.getProperty("path.mapperXML");
		String clazzName = StringUtil.convertUnderline(table.getTableName(), true);
		String path = pathMapperXML + "/" + clazzName + "Mapper.xml";
		
		String customCode = readCustomCode(path);//mapperXML中自定义部分不重写
		String packageMapper = GenConfigHelper.getProperty("package.mapper");
		String namespace = packageMapper + "." + clazzName + "Mapper";
		
		String packagePo = GenConfigHelper.getProperty("package.po");
		String typePo = packagePo+ "." + clazzName;
		
		String packageDao = GenConfigHelper.getProperty("package.mapper");
		String baseMapperParamsType = packageDao + ".BaseMapperParams";
		
		MapperXMLFile mapperXMLFile = new MapperXMLFile();
		mapperXMLFile.setNamespace(namespace);
		mapperXMLFile.setTableName(table.getTableName());
		mapperXMLFile.setCustomCode(customCode);
		mapperXMLFile.setBaseMapperParamsType(baseMapperParamsType);
		
		List<ClazzProperty> properties = new ArrayList<>();
		List<String> columnNames = new ArrayList<>();
		BaseResultMap baseResultMap = new BaseResultMap();
		baseResultMap.setType(typePo);
		if (columns != null && columns.size() > 0) {
			ClazzProperty property = null;
			for (ColumnPO column : columns) {
				property = ClazzProperty.getFromPO(column);
				columnNames.add(property.getColumnName());
				
				if(property.isPrimaryKey()) {
					baseResultMap.setId(property);
				} else {
					properties.add(property);
				}
			}
			baseResultMap.setResults(properties);
		}
		
		mapperXMLFile.setBaseColumnList(String.join(",", columnNames));
		mapperXMLFile.setBaseResultMap(baseResultMap);
		
		File file = new File(path);
		file.getParentFile().mkdirs();
		TemplateHelper.getInstance().process("MapperXML", path, mapperXMLFile);	
	}
	
	/**
	 * 获取自定义部分代码
	 * @param path
	 * @return
	 */
	private String readCustomCode(String path) {
		String customCode = "";
		File file = new File(path);
		if (file.exists()) {
			String fileStr = null;
			
			BufferedReader br = null;
			try {
				StringBuffer sb = new StringBuffer();
				br = new BufferedReader(new FileReader(file));
				String line = "";
				while((line = br.readLine()) != null) {
					sb.append(line);
					sb.append("\r\n");
				}
				if (sb.length() > 0) {
					fileStr = sb.substring(0, sb.lastIndexOf("\r\n"));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if (StringUtil.isNotNull(fileStr)) {
				int customCodeMarkerIndex = fileStr.indexOf(CUSTOM_CODE_MARKER) + CUSTOM_CODE_MARKER.length();
				int endIndex = fileStr.indexOf("</mapper>");
				if(customCodeMarkerIndex > -1 && endIndex > -1) {
					customCode = fileStr.substring(customCodeMarkerIndex, endIndex);
				} else if(customCodeMarkerIndex > -1) {
					customCode = fileStr.substring(customCodeMarkerIndex);
				}
				customCode = customCode.trim();
			}
		}
		return customCode.trim();
	}

}
